Page({
  data: {
    // 用户登录状态
    isLogin: false,
    userPhone: '',

    // 市场概况
    marketOverview: {
      shanghai: { name: '上证指数', code: '000001', price: '3245.67', change: '+0.85%', color: '#e74c3c' },
      shenzhen: { name: '深证成指', code: '399001', price: '12456.78', change: '+1.25%', color: '#e74c3c' },
      chuangye: { name: '创业板指', code: '399006', price: '2567.89', change: '-0.45%', color: '#2ecc71' }
    },



    // 涨幅榜前5
    topGainers: [],

    // 跌幅榜前5
    topLosers: [],

    // 成交额榜前5
    topVolume: [],

    // 当前显示的榜单类型
    currentRankType: 'gainers',



    // 股票搜索
    searchKeyword: '',
    searchResults: [],
    showSearchResults: false,

    // 加载状态
    loading: true
  },

  onLoad: function (options) {
    // 检查登录状态
    this.checkLoginStatus();

    // 加载首页数据
    this.loadHomeData();
  },

  onShow: function () {
    // 每次显示页面时刷新登录状态
    this.checkLoginStatus();
  },

  // 检查登录状态
  checkLoginStatus: function () {
    const app = getApp();
    this.setData({
      isLogin: app.globalData.isLogin || false,
      userPhone: app.globalData.userPhone || ''
    });
  },

  // 加载首页数据
  loadHomeData: function () {
    // 加载市场概况
    this.loadMarketOverview();

    // 加载股票排行榜
    this.loadStockRankings();
  },

  // 加载市场概况
  loadMarketOverview: function () {
    const that = this;

    // 获取主要指数数据
    wx.request({
      url: 'https://push2.eastmoney.com/api/qt/ulist.np/get',
      data: {
        fltt: 2,
        invt: 2,
        fields: 'f2,f3,f4,f12,f14',
        secids: '1.000001,0.399001,0.399006', // 上证指数、深证成指、创业板指
        ut: 'bd1d9ddb04089700cf9c27f6f7426281'
      },
      success(res) {
        if (res.data && res.data.data && res.data.data.diff) {
          const indices = res.data.data.diff;
          const overview = {};

          indices.forEach(item => {
            const change = item.f3 || 0;
            const changeStr = change > 0 ? `+${change.toFixed(2)}%` : `${change.toFixed(2)}%`;
            const color = change >= 0 ? '#e74c3c' : '#2ecc71';

            if (item.f12 === '000001') {
              overview.shanghai = {
                name: '上证指数',
                code: '000001',
                price: item.f2 ? item.f2.toFixed(2) : '--',
                change: changeStr,
                color: color
              };
            } else if (item.f12 === '399001') {
              overview.shenzhen = {
                name: '深证成指',
                code: '399001',
                price: item.f2 ? item.f2.toFixed(2) : '--',
                change: changeStr,
                color: color
              };
            } else if (item.f12 === '399006') {
              overview.chuangye = {
                name: '创业板指',
                code: '399006',
                price: item.f2 ? item.f2.toFixed(2) : '--',
                change: changeStr,
                color: color
              };
            }
          });

          that.setData({
            marketOverview: overview
          });
        }
      },
      fail(err) {
        console.error('获取市场概况失败:', err);
      }
    });
  },



  // 加载股票排行榜
  loadStockRankings: function () {
    // 加载涨幅榜
    this.loadRankingData('gainers', 'f3', 1);
    // 加载跌幅榜
    this.loadRankingData('losers', 'f3', 0);
    // 加载成交额榜
    this.loadRankingData('volume', 'f5', 1);
  },

  // 加载排行榜数据
  loadRankingData: function (type, sortField, sortOrder) {
    const that = this;

    wx.request({
      url: 'https://push2.eastmoney.com/api/qt/clist/get',
      data: {
        pn: 1,
        pz: 5,
        po: sortOrder,
        np: 1,
        ut: 'bd1d9ddb04089700cf9c27f6f7426281',
        fltt: 2,
        invt: 2,
        fid: sortField,
        fs: 'm:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23',
        fields: 'f2,f3,f4,f5,f12,f14'
      },
      success(res) {
        if (res.data && res.data.data && res.data.data.diff) {
          const stocks = res.data.data.diff.map(item => {
            const price = item.f2 ? item.f2.toFixed(2) : '--';
            const change = item.f3 || 0;
            const changeStr = change > 0 ? `+${change.toFixed(2)}%` : `${change.toFixed(2)}%`;
            const volume = item.f5 ? (item.f5 / 100000000).toFixed(2) + '亿' : '--';

            let stockCode = item.f12;
            if (stockCode.startsWith('6')) {
              stockCode = 'sh' + stockCode;
            } else {
              stockCode = 'sz' + stockCode;
            }

            return {
              name: item.f14 || '--',
              code: stockCode,
              price: price,
              change: changeStr,
              volume: volume
            };
          });

          if (type === 'gainers') {
            that.setData({ topGainers: stocks });
          } else if (type === 'losers') {
            that.setData({ topLosers: stocks });
          } else if (type === 'volume') {
            that.setData({ topVolume: stocks });
          }
        }

        // 检查是否所有数据都加载完成
        that.checkLoadingComplete();
      },
      fail(err) {
        console.error(`获取${type}排行榜失败:`, err);
        that.checkLoadingComplete();
      }
    });
  },

  // 检查加载完成
  checkLoadingComplete: function () {
    if (this.data.topGainers.length > 0 &&
      this.data.topLosers.length > 0 &&
      this.data.topVolume.length > 0) {
      this.setData({
        loading: false
      });
    }
  },

  // 切换排行榜类型
  switchRankType: function (e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentRankType: type
    });
  },

  // 跳转到登录页面
  goToLogin: function () {
    wx.navigateTo({
      url: '/pages/login/index'
    });
  },

  // 快捷功能跳转
  goToPage: function (e) {
    const url = e.currentTarget.dataset.url;
    console.log('跳转到页面:', url);

    if (url) {
      wx.navigateTo({
        url: url,
        success: function () {
          console.log('跳转成功:', url);
        },
        fail: function (err) {
          console.error('跳转失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else {
      console.error('跳转URL为空');
      wx.showToast({
        title: '页面路径错误',
        icon: 'none'
      });
    }
  },

  // 跳转到股票详情
  goToStockDetail: function (e) {
    const stock = e.currentTarget.dataset.stock;
    wx.navigateTo({
      url: `/pages/stock/index?code=${stock.code}`
    });
  },



  // 查看更多排行榜
  viewMoreRanking: function () {
    wx.navigateTo({
      url: '/pages/market/index'
    });
  },

  // 股票搜索
  onSearchInput: function (e) {
    const keyword = e.detail.value.trim();
    this.setData({
      searchKeyword: keyword
    });

    if (!keyword) {
      this.setData({
        showSearchResults: false,
        searchResults: []
      });
      return;
    }

    // 防抖搜索
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      this.searchStocks(keyword);
    }, 500);
  },

  // 执行股票搜索
  searchStocks: function (keyword) {
    const that = this;

    wx.request({
      url: 'https://searchapi.eastmoney.com/api/suggest/get',
      data: {
        input: keyword,
        type: 14,
        token: 'D43BF722C8E33BDC906FB84D85E326E8',
        count: 5
      },
      success(res) {
        if (res.data && res.data.QuotationCodeTable && res.data.QuotationCodeTable.Data) {
          const results = res.data.QuotationCodeTable.Data.filter(item => {
            return item.Classify === 'AStock' && (item.SecurityTypeName === '沪A' || item.SecurityTypeName === '深A');
          });

          that.setData({
            searchResults: results,
            showSearchResults: true
          });
        }
      },
      fail(err) {
        console.error('股票搜索失败:', err);
      }
    });
  },

  // 选择搜索结果
  selectSearchResult: function (e) {
    const stock = e.currentTarget.dataset.stock;

    let stockCode = stock.Code;
    if (stock.SecurityTypeName === '沪A') {
      stockCode = 'sh' + stock.Code;
    } else if (stock.SecurityTypeName === '深A') {
      stockCode = 'sz' + stock.Code;
    }

    this.setData({
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false
    });

    wx.navigateTo({
      url: `/pages/stock/index?code=${stockCode}`
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.setData({
      loading: true
    });
    this.loadHomeData();
    wx.stopPullDownRefresh();
  }
});